package com.mini.auth.controller;

import com.mini.common.core.result.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.Map;

/**
 * 处理认证请求
 */
@RestController
@RequestMapping("/oauth")
public class OAuthController {

    @Autowired
    private TokenEndpoint tokenEndpoint;

    /**
     * 获取token
     */
    @PostMapping("/token")
    public Object postAccessToken(Principal principal,
            @RequestBody Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        /**
         * 获取登录认证的客户端ID
         *
         * 兼容两种方式获取Oauth2客户端信息（client_id、client_secret）
         * 方式一：client_id、client_secret放在请求路径中
         * 方式二：放在请求头（Request Headers）中的Authorization字段，且经过加密，例如 Basic Y2xpZW50OnNlY3JldA== 明文等于 client:secret
         */
        return RestResponse.ok(tokenEndpoint.postAccessToken(principal, parameters).getBody());
    }
}
